from flask import Flask, render_template, jsonify
from flask_sqlalchemy import SQLAlchemy
from config import Config
from models import db, HotSearch
from datetime import datetime, timedelta

app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)


# 创建数据库表
# @app.before_first_request
def create_tables():
    db.create_all()


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/api/hot_searches')
def get_hot_searches():
    # 获取今天的数据
    today = datetime.now().date()
    data = HotSearch.query.filter(HotSearch.create_time >= today).all()

    # 如果没有今天的数据，则返回空数组
    if not data:
        return jsonify([])

    # 将数据转换为字典列表
    result = [item.to_dict() for item in data]

    return jsonify(result)


@app.route('/api/stats')
def get_stats():
    # 获取今天的数据
    today = datetime.now().date()
    data = HotSearch.query.filter(HotSearch.create_time >= today).all()

    if not data:
        return jsonify({
            'total': 0,
            'max_heat': 0,
            'avg_heat': 0,
            'entertainment_percent': 0,
            'new_topics': 0
        })

    # 计算统计数据
    total = len(data)
    max_heat = max(item.num for item in data)
    avg_heat = sum(item.num for item in data) // total if total > 0 else 0

    # 计算娱乐占比
    entertainment_count = sum(1 for item in data if item.flag == '剧集' or item.flag == '演出')
    entertainment_percent = round((entertainment_count / total) * 100) if total > 0 else 0

    # 计算新话题数
    new_topics = sum(1 for item in data if item.label == '新')

    return jsonify({
        'total': total,
        'max_heat': max_heat,
        'avg_heat': avg_heat,
        'entertainment_percent': entertainment_percent,
        'new_topics': new_topics
    })


if __name__ == '__main__':
    app.run(debug=True)